﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json.Linq;

namespace FBEntities.FBObjects.User
{
    public class FBEducation : IFBObject
    {
        public List<FBObject> concentration;
        public FBObject school;
        public FBObject year;

        public FBEducation()
        {
            concentration = new List<FBObject>();
        }

        #region IFBObject Members

        public void Parse(JObject o)
        {
            foreach (FieldInfo field in GetType().GetFields())
            {
                if (o[field.Name] == null)
                    continue;

                if (field.FieldType.GetInterfaces().Count(i => i.Equals(typeof (IFBObject))) > 0)
                {
                    var obj = (IFBObject) Activator.CreateInstance(field.FieldType);
                    var data = o[field.Name] as JObject;
                    obj.Parse(data);
                    field.SetValue(this, obj);
                }
                else if (field.FieldType.GetGenericArguments().Count() > 0 &&
                         field.FieldType.GetGenericArguments()[0].GetInterfaces().Count(i => i.Equals(typeof (IFBObject))) > 0)
                {
                    Type gen = field.FieldType.GetGenericArguments()[0];
                    MethodInfo method = field.FieldType.GetMethod("Add");
                    foreach (JObject inObj in o[field.Name] as JArray)
                    {
                        var obj = (IFBObject) Activator.CreateInstance(gen);
                        obj.Parse(inObj);

                        method.Invoke(field.GetValue(this), new object[] {obj});
                    }
                }
            }
        }

        #endregion
    }
}